$(function() {
  var socket = io()
  console.log(socket)
  var username
  var connected = false
  var $room = $('#room')
  var $newMessage = $('#newMessage')
  var $msgBox = $('#messageList')

  /**
   * 消息模板
   * */
  function chatTpl(opts) {
    var tpl = []
    if (opts.username == username) {
      tpl.push("<li class='message myself'>")
    } else {
      tpl.push("<li class='message'>")
    }
    tpl.push(
      "<div class='head'><img src='../images/avatar.png' alt='头像' /></div>"
    )
    tpl.push(
      "<div class='content'><div class='nickname'>" +
        opts.username +
        "</div><div class='text'>" +
        opts.message +
        '</div></div>'
    )
    tpl.push('</li>')
    return tpl.join('')
  }
  function log(msg, opts = {}) {
    var $el = $('<li>')
      .addClass('log')
      .text(msg)
    addMessageElement($el, opts)
  }
  function addMessageElement(el, opts) {
    var $el = $(el)
    if (opts.prepend) {
      $msgBox.prepend($el)
    } else {
      $msgBox.append($el)
    }
    $msgBox[0].scrollTop = $msgBox[0].scrollHeight
  }
  function printUserNum(data) {
    var message = ''
    message += 'there are ' + data.guestNumber + ' in the room'
    log(message)
  }

  function sendMessage() {
    var msg = $newMessage.val()
    if (msg && connected) {
      $newMessage.val('')
      addChatMessage({
        username: username,
        message: msg
      })
      socket.emit('new message', msg)
    }
  }
  function addChatMessage(data, opts = {}) {
    addMessageElement(chatTpl(data), opts)
  }
  var Chat = function(socket) {
    this.socket = socket
  }
  Chat.prototype = {
    createRoom: function(room) {
      $msgBox.empty()
      socket.emit('create room', room || '温馨小屋')
      // socket.emit('add user', username)
    },
    afterCreated: function(data) {
      if (data.success) {
        $room.html(data.room)
        username = $('#username').text()
        socket.emit('add user', username)
      }
    },
    changeRoom: function(room) {
      socket.emit('change room', room)
    },
    enter: function(data) {
      connected = true
      let message = 'Welcome to ' + data.curRoom
      log(message, {
        prepend: true
      })
      printUserNum(data)
    },
    userJoined: function(data) {
      log(data.username + ' joined')
      printUserNum(data)
    },
    newMessage: function(data) {
      addChatMessage(data)
    },
    disconnect: function() {
      log('you have been disconnected')
    },
    userLeave: function(data) {
      log(data.username + ' has benn leave')
      printUserNum(data)
    },
    reconnect: function() {
      log('you has benn reconnected')
      if (username) {
        socket.emit('add user', username)
      }
    },
    reconnectError: function() {
      log('attempt to reconnect has failed')
    }
  }

  socket.on('connect', function() {
    log('连接成功')
    var chat = new Chat(socket)
    chat.createRoom()
    socket.on('create room', chat.createRoom)
    socket.on('after created', chat.afterCreated)
    socket.on('enter', chat.enter)
    socket.on('user joined', chat.userJoined)
    socket.on('new message', chat.newMessage)
    socket.on('disconnect', chat.disconnect)
    socket.on('user leave', chat.userLeave)
    socket.on('reconnect', chat.reconnect)
    socket.on('reconnect_error', chat.reconnectError)

    $('#sendBtn').on('click', function() {
      sendMessage()
    })
    $(window).keydown(event => {
      // Auto-focus the current input when a key is typed
      if (!(event.ctrlKey || event.metaKey || event.altKey)) {
        $newMessage.focus()
      }
      if (event.which === 13) {
        sendMessage()
      }
    })

    $('#roomList').on('click', 'li', function() {
      let _this = $(this)
      _this
        .addClass('active')
        .siblings('li')
        .removeClass('active')
      var room = _this.text()
      chat.changeRoom(room)
    })
  })
})
